<?php

namespace App\Services\Tcc\Process;

use App\Services\Tcc\Transaction\Participant;
use Ethansmart\HttpBuilder\Builder\HttpClientBuilder;

class Process
{
    protected $httpClient ;
    protected $participant ;

    function  __construct(Participant $participant)
    {
        $this->httpClient = HttpClientBuilder::create()->build();
        $this->participant = $participant;
    }

    /**
     * @param $parts
     * @return array
     * @example
     * {"participantLink":
     *   {"uri":"http://www.example.com/part/123",
     *    "expires":"2014-01-11T10:15:54Z"}
     * }
     *
     */
    public function processTry($parts)
    {   return $this->participant->TccTry();
        $participantLinks = array();
        foreach ($parts as $item) {
            $participantLink = $this->processRequest($item['uri'], $item['data']);
            if ($participantLink->code!=0) {
                return \Exception('Tcc Try Error');
            }
            $participantLinks[] = $participantLink->participant;
        }
//        return $participantLinks;
        try {
            $result =  $this->processConfirm($participantLinks);
            if ($result->code!=0) {
                $this->processCancel($participantLinks);
            }
        } catch (\Exception $e) {
            $this->processCancel($participantLinks);
        }

        return ['code'=>0, 'msg'=>'ok'];
    }

    public function processConfirm($participantLinks)
    {
        foreach ($participantLinks as $item) {
            $confirmResult = $this->processRequest($item['uri'], $item['data']);
            if ($confirmResult->code!=0) {
                throw new Exception("Tcc Confirm Error");
            }
        }
        return ['code'=>0, 'msg'=>'ok'];
    }

    public function processCancel($participantLinks)
    {
        foreach ($participantLinks as $item) {
            $confirmResult = $this->processRequest($item['uri'], $item['data']);
            if ($confirmResult->code!=0) {
                throw new Exception("Tcc Cancel Error");
            }
        }
        return ['code'=>0, 'msg'=>'ok'];
    }

    protected function processRequest($url, $data)
    {
        $data = [
            'uri'=>$url,
            'params'=>$data
        ];

        return $this->httpClient
            ->setHeaders('Content-Type:application/json')
            ->setHeaders('X-HTTP-Method-Override:GET')
            ->Get($data);
    }
}